<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <!-- 添加分类按钮 -->

    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          >
        </el-col>
      </el-row>
      <table-tree
        :data="cateList"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        class="table-tree"
      >
        <!-- 是否有效插槽 -->
        <template slot="isOk" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: green"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag type="success" v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag type="warning" v-else>三级</el-tag>
        </template>
        <template slot="action" slot-scope="scope">
          <el-button
            type="primary"
            icon="el-icon-edit"
            size="mini"
            @click="showEditDialog(scope.row)"
            >编辑</el-button
          >
          <el-button type="danger" icon="el-icon-delete" size="mini"
            @click="deleteCate(scope.row)"
            >删除</el-button
          >
        </template>
      </table-tree>
    </el-card>

    <!-- 分页区域 -->
    <el-pagination
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
      :current-page="queryInfo.pagenum"
      :page-sizes="[5, 10, 15, 20]"
      :page-size="queryInfo.pagesize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    >
    </el-pagination>

    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @closed="addCateDialogClosed"
    >
      <el-form
        ref="addCateForm"
        :model="addCateForm"
        :rules="addCateFormRule"
        label-width="100px"
      >
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父类级别：">
          <el-cascader
            expand-trigger="hover"
            :options="parentCateList"
            :props="cascaderProp"
            v-model="selectedKeys"
            @change="selectedKeysChanged"
            clearable
            ref="cascader"
          >
          </el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑分类信息对话框 -->
    <el-dialog
      title="编辑分类信息"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @closed="editCateClosed"
    >
      <el-form ref="editCateForm" :model="editCateForm" :rules="editCateFormRule" label-width="100px">
        <el-form-item label="分类名称：" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCate"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      /* 商品分类数据列表，默认为空 */
      cateList: [],
      /* 获取商品分类数据请求的参数 */
      queryInfo: {
        type: '',
        pagenum: 1,
        pagesize: 10,
      },
      /* 商品分类总条数 */
      total: 0,
      /* 商品分类表列详情 */
      columns: [
        {
          label: '分类名称',
          prop: 'cat_name',
        },
        {
          label: '是否有效',
          type: 'template',
          template: 'isOk',
        },
        {
          label: '排序',
          prop: 'cat_level',
          type: 'template',
          template: 'level',
        },
        {
          label: '操作',
          type: 'template',
          template: 'action',
        },
      ],
      /* 添加分类对话框的显示与隐藏 */
      addCateDialogVisible: false,
      parentCateList: [],
      /* 添加分类对话框表单 */
      addCateForm: {
        cat_name: '',
        cat_pid: 0,
        cat_level: 0,
      },
      /* 添加分类对话框表单验证规则 */
      addCateFormRule: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' },
        ],
      },
      cascaderProp: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        checkStrictly: true,
      },
      selectedKeys: [],
      /* 编辑分类信息 */
      /* 控制编辑对话框的显示与隐藏 */
      editCateDialogVisible: false,
      editCateForm: {
        cat_id: '',
        cat_name: ''
      },
      editCateFormRule: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur'}
        ]
      }
    }
  },
  created() {
    this.getCateList()
  },
  methods: {
    async getCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: this.queryInfo,
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      this.cateList = res.data.result
      this.total = res.data.total
    },
    handleSizeChange(newSize) {
      this.queryInfo.pagesize = newSize
      this.getCateList()
    },
    handleCurrentChange(newPage) {
      this.queryInfo.pagenum = newPage
      this.getCateList()
    },
    /* 点击添加分类按钮 */
    showAddCateDialog() {
      this.addCateDialogVisible = true
      this.getParentCateList()
      //  console.log('1----'+this.cateList)
      // console.log('2----'+this.parentCateList)
    },
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 2 },
      })
      if (res.meta.status !== 200) {
        return this.$message.error('获取父级列表失败！')
      }
      this.parentCateList = res.data
      console.log(res)
    },
    selectedKeysChanged() {
      // console.log(this.selectedKeys)
      /* 在点击的时候收起下拉框 */
      if (this.selectedKeys.length > 0) {
        this.addCateForm.cat_pid =
          this.selectedKeys.length > 0
            ? this.selectedKeys[this.selectedKeys.length - 1]
            : 0
        this.addCateForm.cat_level = this.selectedKeys.length
      } else {
        this.addCateForm.cat_pid = 0
        this.addCateForm.cat_level = 0
      }
      if (this.$refs.cascader) {
        this.$refs.cascader.dropDownVisible = false
      }
    },
    /* 添加分类确认按钮 */
    addCate() {
      this.$refs.addCateForm.validate(async (value) => {
        if (!value) {
          return this.$message.warning('请输入商品分类名称！')
        } else {
          const { data: res } = await this.$http.post(
            'categories',
            this.addCateForm
          )
          if (res.meta.status !== 201) {
            return this.$message.error('创建商品分类失败！')
          }
          this.$message.success('创建商品分类成功！')
          this.addCateDialogVisible = false
          this.getCateList()
        }
      })
    },
    addCateDialogClosed() {
      this.$refs.addCateForm.resetFields()
      this.selectedKeys = []
      this.addCateForm.cat_pid = 0
      this.addCateForm.cat_level = 0
    },
    /* 编辑 */
    /* 显示编辑分类对话框 */
    showEditDialog(cate) {
      this.editCateDialogVisible = true
      this.editCateForm.cat_name = cate.cat_name
      this.editCateForm.cat_id = cate.cat_id
    },
    /* 点击按钮确认编辑分类信息 */
    editCate() {
      this.$refs.editCateForm.validate(async value => {
        if(!value) {
          return 
        }else {
          const {data: res} = await this.$http.put('categories/'+this.editCateForm.cat_id, {
            cat_name: this.editCateForm.cat_name
          })
          if(res.meta.status !== 200) {
            return this.$message.error('分类信息修改失败！')
          }
          this.$message.success('分类信息修改成功！')
          this.editCateDialogVisible = false
          this.getCateList()
        }
      })
    },
    /* 编辑对话框关闭时清空表单 */
    editCateClosed() {
      this.$refs.editCateForm.resetFields()
      this.editCateForm.cat_id = ''
    },
    /* 删除分类 */
    deleteCate(cate) {
      this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async ()=> {
          const {data: res} = await this.$http.delete('categories/'+cate.cat_id)
          if(res.meta.status !== 200) {
            return this.$message.error('商品分类删除失败！')
          }
          this.$message.success(cate.cat_name+'—分类删除成功！')
          this.getCateList()
        })
    }
  },
}
</script>

<style lang="less" scoped>
.table-tree {
  margin-top: 15px;
}
.el-cascader {
  width: 100%;
}
</style>